import { _decorator, Component, Label, Node, sys } from 'cc';
const { ccclass, property } = _decorator;
import { director } from 'cc';
import { ResultView } from '../view/ResultView';

// 声明全局 tt 对象
declare const tt: any;




@ccclass('MainDian')
export class MainDian extends Component {
    appid:string = "2bajh7i96gn3lc9a40";
    sear:string = "SHI0yMzyjYTHs3snPRijQg";

    //ttLoginUrl:string  = "https://www.chuxinwangluo.asia/index.php/tt/login";
    //ttMainDianUrl:string =  "https://www.chuxinwangluo.asia/index.php/tt/index";

    // 直接保存JSON对象
    private jsonData: any = {};
    private static instance: MainDian;
    private callback;


    @property(Label)
    label: Label = null;


    protected onLoad(): void {
        if (MainDian.instance) {
            this.node.destroy(); // 如果已存在，销毁新实例
            return;
        }
        MainDian.instance = this;
        // 使节点常驻（跨场景不销毁）
        director.addPersistRootNode(this.node);
    }

    public static getInstance(): MainDian {
        return MainDian.instance;
    }
    public updateIdLabel(id: string) {
        if (this.label) {
            this.label.string = `ID: ${id}`; 
        } else {
            console.warn('请先在编辑器中关联idLabel组件');
        }
    }
    
    start() {
        // tt.getUserInfo({  
        //     success: (result) => {  
        //         console.log("获取用户信息成功：" + JSON.stringify(result));
        //         this.updateIdLabel(result.id);
        //     },  
        //     fail: (error) => {  
        //         console.log("获取用户信息失败: " + JSON.stringify(error));  
        //     },  
        //     complete:() => {  
        //         console.log("获取用户信息完成");  
        //     }  
        // });  

        tt.login({  
            success: (res) => {          
                console.log("TT Code: " + res.code); 

                let xhr = new XMLHttpRequest();
                let url = "https://www.chuxinwangluo.asia/index.php/tt/login";
                let params = {
                    appid: this.appid,
                    code: res.code
                };
                // 将对象转换为表单格式字符串
                let formData = Object.keys(params).map(key => {
                    return encodeURIComponent(key) + "=" + encodeURIComponent(params[key]);
                }).join("&");
                xhr.open("POST", url, true);
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");  
                xhr.onreadystatechange = ()=> {
                    if (xhr.readyState === 4 || xhr.readyState === 18) {
                        if (xhr.status === 200) {
                            try {
                                let response = JSON.parse(xhr.responseText);
                                // userid
                                console.log(response); 
                                console.log("userid: " + response.data);

                                this.updateIdLabel(response.data.user_id);
                                try {  
                                const res = tt.getSystemInfoSync()  
                                    this.jsonData = {
                                        "brand" : res.brand,
                                        "app_name" : res.host.env,
                                        "hostname" : 1,
                                        "appid" :res.host.appId,
                                        "model" :  res.model,
                                        "open_id" : response.data.openid,
                                        "platform":res.platform,
                                        "system":res.system
                                    }
                                    console.log(this.jsonData);
                                    sys.localStorage.setItem('gameData', JSON.stringify(this.jsonData));
                                }catch (e) {  
                                    // Do something when catch error  
                                    console.log("getSystemInfoSync error");
                                }  

                            } catch (e) {
                                console.error("JSON解析错误:", e);
                            }
                        } else {
                            console.error("请求失败:", xhr.status);
                        }
                    }
                };

                xhr.send(formData);

                },  
            fail: function(error) {  
                console.error("登录失败：" +  error);  
            },  
            complete: function() {  
                console.log("登录完成： login complete");  
            }  
            }
        )

        // let result = tt.getLaunchOptionsSync();
        // let queryJson = JSON.stringify(result);
        // console.log("getLaunchOptionsSync:" + queryJson);        
        // this.callback = queryJson.callback;
        // this.sendGetRequest(1,this.callback);
    }

    public Maindian(callback = null){
        console.log("Maindian");
        let xhr = new XMLHttpRequest();
        let url = "https://www.chuxinwangluo.asia/index.php/tt/index";



        

        const savedData = sys.localStorage.getItem('gameData');
        if (savedData) {
            const parsedData = JSON.parse(savedData);
            console.log("读取的数据：", parsedData);
            
            // 将对象转换为表单格式字符串
            let formData = Object.keys(parsedData).map(key => {
                return encodeURIComponent(key) + "=" + encodeURIComponent(parsedData[key]);
            }).join("&");
            
            xhr.open("POST", url, true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");  
            xhr.onreadystatechange = ()=> {
                if (xhr.readyState === 4 || xhr.readyState === 18) {
                    if (xhr.status === 200) {
                        try {
                            let response = JSON.parse(xhr.responseText);
                            console.log(response);                                                         
                        } catch (e) {
                            console.error("JSON解析错误:", e);
                        }
                    } else {
                        console.error("请求失败:", xhr.status);
                    }
                }
            }
            xhr.send(formData);
    }
    }

    sendGetRequest(eventType:number,callback:string) {
        
        let baseUrl = "https://ad.partner.gifshow.com/track/activate";
        
        let params = new URLSearchParams();
        params.append('event_type',eventType.toString());
        let currentTimeStamp = Date.now();
        params.append('event_time', currentTimeStamp.toString());
        params.append('callback',callback);
        
        let UploadKS =  `${baseUrl}?${params.toString()}`;

        const xhr = new XMLHttpRequest();        
        xhr.open("GET", UploadKS, true);

        xhr.onload = () => {
            if (xhr.status >= 200 && xhr.status < 300) {
                console.log("响应数据:", xhr.responseText);
            } else {
                console.error("请求失败，状态码:", xhr.status);
            }
        };

        xhr.onerror = () => {
            console.error("网络错误");
        };
        
        xhr.send();
    }


    

}
